import cv2
import numpy as np
from matplotlib import pyplot as plt


# 在一张整体背景截图中去寻找局部图片的位置
def searchPicInPic(partPicImg, FullPicImg):
    # img = cv2.imread(FullPicImg, 0)
    img = FullPicImg
    img2 = img.copy()
    # template = cv2.imread(partPicImg, 0)
    template = partPicImg
    w, h = template.shape[::-1]
    # All the 6 methods for comparison in a list
    methods = ['cv2.TM_CCOEFF', 'cv2.TM_CCOEFF_NORMED', 'cv2.TM_CCORR',
               'cv2.TM_CCORR_NORMED', 'cv2.TM_SQDIFF', 'cv2.TM_SQDIFF_NORMED']
    # 循环中只使用其中一个（效果不好，可以换）
    methods = ['cv2.TM_SQDIFF_NORMED']
    for meth in methods:
        img = img2.copy()
        # eval 语句用来计算存储在字符串中的有效 Python 表达式
        method = eval(meth)
        # 模板匹配
        res = cv2.matchTemplate(img, template, method)
        # 寻找最值
        min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
        # 使用不同的比较方法，对结果的解释不同

        if method in [cv2.TM_SQDIFF, cv2.TM_SQDIFF_NORMED]:
            top_left = min_loc
        else:
            top_left = max_loc
        bottom_right = (top_left[0] + w, top_left[1] + h)
        # 以下是具体现显示找到的图片，而我要的是坐标
        # cv2.rectangle(img, top_left, bottom_right, 255, 2)
        # plt.subplot(121), plt.imshow(res, cmap='gray')
        # plt.title('Matching Result'), plt.xticks([]), plt.yticks([])
        # plt.subplot(122), plt.imshow(img, cmap='gray')
        # plt.title('Detected Point'), plt.xticks([]), plt.yticks([])
        # plt.suptitle(meth)
        # plt.show()
    # 折中的找到后中心位置的坐标
    return ((top_left[0] + bottom_right[0]) / 2, (top_left[1] + bottom_right[1]) / 2)


if __name__ == '__main__':
    a = 'debug1'
    b = searchPicInPic('../demo/ocrtest/GridTop1.jpg', '../demo/searchpic/full_grid.jpg')
    a = 'debug2'